package humanMirror.controller.actions;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;
import humanMirror.service.dbconnection.DBConnection;
import humanMirror.service.dbconnection.SQLiteConnection;


public class RegisterAction implements Action{

	private DBConnection dbConnection = new SQLiteConnection();;
	
	private Connection conn = null;
	private ResultSet r =null;
	private PreparedStatement pstmt = null;
	
	public String perform(HttpServletRequest request,
			HttpServletResponse response) {

		String login = request.getParameter("login");
		String password = request.getParameter("password");

//		Pattern p = Pattern.compile("[a-zA-Z0-9]+");
//		Matcher loginMatcher = p.matcher(login);
//		Matcher passwordMatcher = p.matcher(password);
//
//		if (!loginMatcher.matches() || !passwordMatcher.matches()){
//			request.setAttribute("errorMessage", "forbiden symbols in login/password ");
//			return "/error.jsp";
//		}

		try{
			conn = dbConnection.getConnection();
			
			pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE LOGIN=?1");			
			pstmt.setString(1, login);
			pstmt.execute();
			
			r = pstmt.getResultSet();
			
			if (r.next()){
				request.setAttribute("errorMessage", "User with this login already exist");
				return "/error.jsp";
			} else {
				pstmt = conn.prepareStatement("INSERT INTO Users (Login,Password) VALUES (?1,?2)");
				pstmt.setString(1, login);
				pstmt.setString(2, password);
				pstmt.execute();

				HttpSession session = request.getSession(true);
				session.setAttribute("user", login);
				session.setAttribute("controller", new Controller(new Human()));
				session.setAttribute("questionNumber", 0);

				return "/main.jsp";	
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}		
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}//finally
		return null;
	}//perform

	public void setConnection(DBConnection dbConnection){
		this.dbConnection = dbConnection;
	}
	
}
